<?php

namespace plugin\ycMassage\app\api\controller;

use app\common\manager\SettingsMgr;
use app\common\utils\Password;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\model\MassageUserDealer;
use plugin\ycMassage\app\model\MassageUserWechat;
use plugin\ycMassage\utils\enum\State;
use plugin\ycMassage\utils\Sms;
use plugin\ycMassage\utils\Str;
use support\Request;
use think\captcha\facade\Captcha;
use think\facade\Cache;
use think\facade\Db;

class LoginController extends BaseController
{
    protected $noNeedLogin = ["login", "wechatLogin", "captcha", "getVcode", "vcode", 'wechatMPCode', 'wechatMP'];
    protected $noNeedAppid = ["captcha"];
    public function login(Request $request)
    {
        $D = $request->post();
        if (empty($D['mobile'])) {
            return $this->fail('请输入手机号');
        }
        if (empty($D['password'])) {
            return $this->fail('请输入密码');
        }
        $appid = $request->appid;
        $MassageUser = MassageUser::where(['saas_appid' => $appid, 'mobile' => $D['mobile']])->find();
        if (!$MassageUser) {
            return $this->fail('用户不存在');
        }
        if(!$MassageUser->password){
            return $this->fail('请使用验证码登录');
        }
        if (!Password::passwordVerify($D['password'], $MassageUser->password)) {
            return $this->fail('密码错误');
        }
        if ($MassageUser->state === State::NO['value']) {
            return $this->fail('该用户已被冻结');
        }
        $MassageUser->last_login_ip = $request->ip();
        $MassageUser->last_login_time = date('Y-m-d H:i:s');
        $MassageUser->save();
        $data = MassageUser::getInfo($MassageUser->id);
        return $this->successRes($data);
    }
    public function wechatLogin(Request $request)
    {
        $redirect = $request->post('redirect');
        $action = $request->post('action');
        $params = $request->post('params');
        $appid = $request->appid;
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize";
        $wxappid = getHpConfig('appid', $appid, 'wx');
        if (!$wxappid) {
            return $this->fail('未配置微信公众号');
        }
        $domain = getHpConfig('domain', (int)$appid, 'plugins_domains');
        $stateObj = ['appid' => $appid, 'redirect' => $redirect, 'puid' => $request->puid,'dealer_uid'=>$request->dealer_uid, 'params' => $params, 'action' => urlencode($action)];
        $stateKey = Str::random(32);
        Cache::set($stateKey, $stateObj, 3600);
        $query = [
            'appid' => $wxappid,
            'redirect_uri' => "{$domain}/{$this->pluginPrefix}/Login/wechatLoginCallback",
            'response_type' => 'code',
            'scope' => 'snsapi_userinfo',
            'state' => $stateKey,
        ];
        $url = $url . '?' . http_build_query($query) . "#wechat_redirect";
        return $this->successRes($url);
    }
    public function vcode(Request $request)
    {
        $D = $request->post();
        if (empty($D['mobile'])) {
            return $this->fail('请输入手机号');
        }
        if (empty($D['vcode'])) {
            return $this->fail('请输入验证码');
        }
        if (Cache::get('vcode.' . $D['mobile']) != $D['vcode']) {
            return $this->fail('验证码错误');
        }
        $appid = $request->appid;
        Db::startTrans();
        try {
            $isRegister = false;
            $MassageUser = MassageUser::where(['saas_appid' => $appid, 'mobile' => $D['mobile']])->find();
            if (!$MassageUser) {
                $pModel = MassageUser::where(['saas_appid' => $appid, 'id' => $request->puid])->find();
                # 注册并登录
                $MassageUser = new MassageUser;
                $MassageUser->saas_appid = $appid;
                $MassageUser->mobile = $D['mobile'];
                $MassageUser->nickname = "游客" . Str::random(6, 1);
                $MassageUser->headimg = getHpConfig('default_avatar', $appid, 'user');
                if ($pModel) {
                    $isRegister = true;
                    $MassageUser->puid = $pModel->id;
                }
                $dealerModel=MassageUser::where(['saas_appid' => $appid, 'id' => $request->dealer_uid])->find();
                if($dealerModel){
                    $MassageUser->dealer_uid=$dealerModel->id;
                    MassageUserDealer::IncPeopleNum($dealerModel->id);
                }
            } else {
                if ($MassageUser->state === State::NO['value']) {
                    throw new \Exception('该用户已被冻结');
                }
            }
            $MassageUser->last_login_ip = $request->ip();
            $MassageUser->last_login_time = date('Y-m-d H:i:s');
            $MassageUser->save();
            if ($isRegister) {
                # 邀新奖励业务
                MassageUser::NewRegisterGift($MassageUser, $pModel);
                # 邀新奖励业务
            }
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
        $data = MassageUser::getInfo($MassageUser->id);
        return $this->successRes($data);
    }
    public function captcha(Request $request)
    {
        return Captcha::create();
    }
    public function getVcode(Request $request)
    {
        $D = $request->post();
        if (empty($D['mobile'])) {
            return $this->fail('请输入手机号');
        }
        $imgcode = getHpConfig('imgcode', $request->appid, 'system');
        if ($imgcode) {
            if (empty($D['imgcode'])) {
                return $this->fail('请输入图形验证码');
            }
            // 对比session中的captcha值
            if (Captcha::check(strtolower($D['imgcode']))) {
                return $this->fail('图形验证码错误');
            }
        }
        $code = Str::random(6, 1);
        Cache::set('vcode.' . $D['mobile'], $code, 300);
        try {
            Sms::main($request->appid, $D['mobile'], $code);
            return $this->success('已发送');
        } catch (\Throwable $th) {
            return $this->fail($th->getMessage());
        }
    }
    public function wechatMPCode(Request $request)
    {
        $appid = $request->appid;
        $code = $request->post('code');
        $confirm= $request->post('confirm');
        if($confirm){
            $data = Cache::get('wechat_code.' . $code);
            if (!$data) {
                return $this->fail('登录信息已过期，请重新授权登录');
            }
            $MassageUserWechat = null;
            if (isset($data->unionid)) {
                $MassageUserWechat = MassageUserWechat::where(['saas_appid' => $appid, 'unionid' => $data->unionid])->find();
            }
            if (!$MassageUserWechat) {
                $MassageUserWechat = MassageUserWechat::where(['saas_appid' => $appid, 'mp_openid' => $data->openid])->find();
            }
            try {
                $data = MassageUser::getInfo($MassageUserWechat->uid);
                return $this->successRes($data);
            } catch (\Throwable $th) {
                return $this->fail($th->getMessage());
            }
        }
        $config = SettingsMgr::group($appid, 'applet');
        if (empty($config['applet_appid']) || empty($config['applet_secret'])) {
            return $this->failFul('请先配置小程序', 12000);
        }
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $Client = new \GuzzleHttp\Client();
        $response = $Client->request('GET', $url, [
            'query' => [
                'appid' => $config['applet_appid'],
                'secret' => $config['applet_secret'],
                'js_code' => $code,
                'grant_type' => 'authorization_code',
            ]
        ]);
        $body = $response->getBody();
        $data = json_decode($body);
        if (isset($data->errcode)) {
            return $this->failFul("[{$data->errcode}]" . $data->errmsg, 12000);
        }
        $MassageUserWechat = null;
        if (isset($data->unionid)) {
            $MassageUserWechat = MassageUserWechat::where(['saas_appid' => $appid, 'unionid' => $data->unionid])->find();
        }
        if (!$MassageUserWechat) {
            $MassageUserWechat = MassageUserWechat::where(['saas_appid' => $appid, 'mp_openid' => $data->openid])->find();
        }
        Cache::set('wechat_code.' . $code, $data, 1800);
        try {
            if ($MassageUserWechat) {
                # 登录并更新用户信息
                $MassageUserWechat->mp_openid = $data->openid;
                if (isset($data->unionid)) {
                    $MassageUserWechat->unionid = $data->unionid;
                }
                $MassageUserWechat->save();
            }else{
                throw new \Exception('用户不存在');
            }
            $data = MassageUser::where(['id'=>$MassageUserWechat->uid])->find();
            return $this->successRes(['nickname'=>$data->nickname,'headimg'=>$data->headimg,'code'=>$code]);
        } catch (\Throwable $th) {
            return $this->fail($th->getMessage());
        }
    }
    public function wechatMP(Request $request)
    {
        $code = $request->post('code');
        $appid = $request->appid;
        $data = Cache::get('wechat_code.' . $code);
        if (!$data) {
            return $this->fail('登录信息已过期，请重新授权登录');
        }
        $avatar = $request->post('avatar');
        $nickname = $request->post('nickname');
        if (empty($avatar) || empty($nickname)) {
            return $this->fail('头像或昵称不能为空');
        }
        Db::startTrans();
        try {
            $isRegister = false;
            $MassageUserWechat = null;
            if (isset($data->unionid)) {
                $MassageUserWechat = MassageUserWechat::where(['saas_appid' => $appid, 'unionid' => $data->unionid])->find();
            }
            if (!$MassageUserWechat) {
                $MassageUserWechat = MassageUserWechat::where(['saas_appid' => $appid, 'mp_openid' => $data->openid])->find();
            }
            if ($MassageUserWechat && $MassageUserWechat->uid) {
                # 登录并更新用户信息
                $MassageUser = MassageUser::where(['id' => $MassageUserWechat->uid])->find();
                if ($MassageUser->state === State::NO['value']) {
                    throw new \Exception('该用户已被冻结');
                }
            } else {
                $pModel = MassageUser::where(['saas_appid' => $appid, 'id' => $request->puid])->find();
                if (!$MassageUserWechat) {
                    $MassageUserWechat = new MassageUserWechat;
                    $MassageUserWechat->saas_appid = $appid;
                    $MassageUserWechat->nickname = $nickname;
                    $MassageUserWechat->headimg = $avatar;
                }
                # 注册并登录
                $MassageUser = new MassageUser;
                $MassageUser->saas_appid = $appid;
                if ($pModel) {
                    $isRegister = true;
                    $MassageUser->puid = $pModel->id;
                }
                $MassageUser->nickname = $MassageUserWechat->nickname;
                $MassageUser->headimg = $MassageUserWechat->headimg;
                $dealerModel=MassageUser::where(['saas_appid' => $appid, 'id' => $request->dealer_uid])->find();
                if($dealerModel){
                    $MassageUser->dealer_uid=$dealerModel->id;
                    MassageUserDealer::IncPeopleNum($dealerModel->id);
                }
            }
            $MassageUserWechat->mp_openid = $data->openid;
            if (isset($data->unionid)) {
                $MassageUserWechat->unionid = $data->unionid;
            }
            $MassageUser->last_login_ip = $request->ip();
            $MassageUser->last_login_time = date('Y-m-d H:i:s');
            $MassageUser->save();
            if ($isRegister) {
                # 邀新奖励业务
                MassageUser::NewRegisterGift($MassageUser, $pModel);
                # 邀新奖励业务
            }
            $MassageUserWechat->uid = $MassageUser->id;
            $MassageUserWechat->save();
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
        $data = MassageUser::getInfo($MassageUser->id);
        return $this->successRes($data);
    }
}
